package com.example.index.tools.glide

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.util.Base64
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import com.bumptech.glide.Glide
import com.bumptech.glide.load.Options
import com.bumptech.glide.load.ResourceDecoder
import com.bumptech.glide.load.Transformation
import com.bumptech.glide.load.engine.Resource
import com.bumptech.glide.load.resource.bitmap.BitmapResource
import com.bumptech.glide.request.RequestOptions
import kotlinx.android.synthetic.main.activity_glide_base64_decoder.*
import java.security.MessageDigest


class GlideBase64DecoderActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(com.example.index.R.layout.activity_glide_base64_decoder)

        /**
         *   @NonNull
        public <Data, TResource> Registry prepend(
        @NonNull Class<Data> dataClass,
        @NonNull Class<TResource> resourceClass,
        @NonNull ResourceDecoder<Data, TResource> decoder) {
        prepend(BUCKET_PREPEND_ALL, dataClass, resourceClass, decoder);
        return this;
        }
         */
        Glide.get(this)
            .registry.append(String::class.java, Bitmap::class.java, GlideBase64Decoder())


    }

    inner class GlideBase64Decoder : ResourceDecoder<String, Bitmap> {

        override fun handles(source: String, options: Options): Boolean {
            return source.startsWith("data:image")
        }

        override fun decode(
            source: String,
            width: Int,
            height: Int,
            options: Options
        ): Resource<Bitmap>? {
            val byteArray = Base64.decode(source, 0)

            return BitmapResource.obtain(
                BitmapFactory.decodeByteArray(byteArray, 0, byteArray.size),
                Glide.get(this@GlideBase64DecoderActivity).bitmapPool
            )
        }

    }

    fun decode(view: View) {

        Glide.with(this)
            .load(base64.text.toString().trim())
            .into(imageview)
    }
}
